package com.jf.demo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.qr_codescan.MipcaActivityCapture;
import com.jf.map.MyOrderMap;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.sys.android.util.DialogFactory;
import com.sys.android.util.FinalUntil;
import com.sys.android.util.HttpRequester;
import com.sys.android.util.HttpRespons;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

@ContentView(R.layout.my_order)
public class MyOrder extends Activity {

	@ViewInject(R.id.spinner1)
	private Spinner spinner1;

	private List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); // 定义显示的内容包装

	private String company[] = FinalUntil.company;

	private String companys[] = FinalUntil.companyPronoun;

	@ViewInject(R.id.editText1)
	private EditText editText1;

	@ViewInject(R.id.listView1)
	private ListView textView7;

	@ViewInject(R.id.button2)
	private Button button2;

	@ViewInject(R.id.button3)
	private Button button3;

	private String phoneTel;
	private Double mapX;
	private Double mapY;
	private String courName;
	private int brandImag;

	private SimpleAdapter simpleAdapter = null; // 进行数据的转换操作

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		ViewUtils.inject(this);// xml视图加载的处理

		ArrayAdapter<String> adspinner1 = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, company);
		adspinner1
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner1.setAdapter(adspinner1);

		textView7.setVisibility(View.INVISIBLE);// 不显示，但是占位置,View.GONE不显示，也不占位置
		button2.setVisibility(View.INVISIBLE);
		button3.setVisibility(View.INVISIBLE);
	}

	public void finishOrder(View v) {
		this.finish();
	}

	public void scanMyOrder(View v) {
		Intent intent = new Intent();
		intent.setClass(MyOrder.this, MipcaActivityCapture.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivityForResult(intent, 1);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case 1:
			if (resultCode == RESULT_OK) {
				Bundle bundle = data.getExtras();
				String code = bundle.getString("result");
				editText1.setText(code);
			}
			break;
		}
	}

	/**
	 * 点击查询时触发
	 * 
	 * @param v
	 */
	public void MyOrderbuttonClick(View v) {
		final Dialog dialog = DialogFactory.creatRequestDialog(MyOrder.this,
				"数据传输中……");
		textView7.setVisibility(View.VISIBLE);
		dialog.show();
		if (spinner1.getSelectedItem().toString().equals("")) {
			Toast.makeText(getApplicationContext(), "请选择快递公司", 0).show();
			return;
		}
		RequestParams params = new RequestParams();
		params.addQueryStringParameter("orderID", editText1.getText()
				.toString());
		HttpUtils http = new HttpUtils();
		http.send(HttpMethod.POST, FinalUntil.ServerAddress
				+ "courierInfornation", params, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				// TODO Auto-generated method stub
				Log.i("Mainmenu", arg1);
			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				// arg0.result返回服务器结果
				dialog.hide();
				Log.i("myorder", arg0.result);
				try {
					JSONObject jsonarr = new JSONObject(arg0.result);
					if (!"null".equals(jsonarr.getString("username"))) {
						phoneTel = jsonarr.getString("username");
						mapX = Double.valueOf(jsonarr.getString("mapX"));
						mapY = Double.valueOf(jsonarr.getString("mapY"));
						courName = jsonarr.getString("realname");
						brandImag = Integer.valueOf(jsonarr.getString("brand"));
						button2.setVisibility(View.VISIBLE);
						button3.setVisibility(View.VISIBLE);
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		});
		try {
			HttpRequester request = new HttpRequester();
			HttpRespons hr = request
					.sendGet("http://www.kuaidi100.com/query?type="
							+ companys[spinner1.getSelectedItemPosition()]
							+ "&postid=" + editText1.getText().toString());
			String resultStr = hr.getContent();
			JSONObject jsonObj = new JSONObject(resultStr);
			if ("200".equals(jsonObj.get("status").toString())) {
				JSONArray jsonarr = jsonObj.getJSONArray("data");
				list = new ArrayList<Map<String, Object>>();
				String contentPhoneNum = "";
				for (int x = 0; x < jsonarr.length(); x++) {
					Map<String, Object> map = new HashMap<String, Object>(); // 定义Map集合，保存每一行数据
					contentPhoneNum += jsonarr.getJSONObject(x).getString("context");
					String str = jsonarr.getJSONObject(x).getString("context")
							+ "\n" + jsonarr.getJSONObject(x).getString("time");
					map.put("sendName", str); // 与data_list.xml中的TextView组加匹配
					map.put("icon", R.drawable.top_jiantou);
					this.list.add(map); // 保存了所有的数据行
				}
				Analytical(contentPhoneNum);
				this.simpleAdapter = new SimpleAdapter(this, this.list,
						R.layout.my_order_list, new String[] { "sendName",
								"icon" } // Map中的key的名称
						, new int[] { R.id.list_text_1, R.id.list_image_1 }); // 是data_list.xml中定义的组件的资源ID
				this.textView7.setAdapter(this.simpleAdapter);

			} else {
				Toast.makeText(getApplicationContext(), "暂无信息", 0).show();
			}
		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "网络请求异常", 0).show();
		}
	}

	/**
	 * 查询后，打电话
	 */
	public void MyOrderCallClick(View v) {
		Intent intent = new Intent();
		intent.setAction("android.intent.action.CALL");
		intent.setData(Uri.parse("tel:" + phoneTel));
		startActivity(intent);
	}

	/**
	 * 查询后，地图模式
	 */
	public void MyOrderMapClick(View v) {
		Intent intent = new Intent();
		intent.putExtra("mapX", mapX);
		intent.putExtra("mapY", mapY);
		intent.putExtra("courName", courName);
		intent.putExtra("brandImag", brandImag);
		intent.setClass(v.getContext(), MyOrderMap.class);
		startActivity(intent);
	}

	/**
	 * 字符串解析方法
	 */
	public void Analytical(String str) {

		String phoneCard = "";

		String regEx = "[^0-9]";// 数字统配正则
		Pattern p_m = Pattern.compile(regEx);// 电话号码统配正则
		Matcher m_p = p_m.matcher(str);
		str = m_p.replaceAll("").trim();

		regEx = "^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
		Pattern p = Pattern.compile(regEx);// 电话号码统配正则
		Matcher m = p.matcher(str);
		if (m.find()) {
			phoneCard = m.replaceAll("").trim();

			RequestParams params = new RequestParams();
			params.addQueryStringParameter("phoneNum", phoneCard);
			HttpUtils http = new HttpUtils();
			http.send(HttpMethod.POST, FinalUntil.ServerAddress
					+ "findCouriers", params, new RequestCallBack<String>() {

				@Override
				public void onFailure(HttpException arg0, String arg1) {
					// TODO Auto-generated method stub
					Log.i("", arg1);
				}

				@Override
				public void onSuccess(ResponseInfo<String> arg0) {
					// arg0.result返回服务器结果

					try {
						JSONObject jsonarr = new JSONObject(arg0.result);
						if (jsonarr.length() > 0) {

							phoneTel = jsonarr.getString("username");
							mapX = Double.valueOf(jsonarr.getString("mapX"));
							mapY = Double.valueOf(jsonarr.getString("mapY"));
							courName = jsonarr.getString("realname");
							brandImag = Integer.valueOf(jsonarr
									.getString("brand"));
							button2.setVisibility(View.VISIBLE);
							button3.setVisibility(View.VISIBLE);

						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}
			});
		}
	}
}
